class timer {
  constructor() {
    this.isActive = false; // 倒计时是否已开启
    this.action = null; // 传入倒计时方法
    this.timeoutObject = null; // 页面当前的倒计时方法
    this.intervalTime = null;
  }

  /**
   * 调用倒计时
   * @param {function} func 执行的回调
   * @param {Number} time 倒计时时间
   * @param {Boolean} autostart 是否开启倒计时
   * 常用方法  ： show 设置倒计时
   *             stop 结束倒计时
   *             pause 暂停倒计时
   *             play  开始倒计时
   */
  show(func, time, autostart) {
    this.set(func, time, autostart);
    return this;
  }

  set(func, time, autostart) {
    let _func = func;
    if (typeof _func === 'function') {
      this.action = _func;
    }
    if (!isNaN(time)) {
      this.intervalTime = time;
    }
    if (autostart && !this.isActive) {
      this.isActive = true;
      this.timer();
    }
    return this;
  }

  play() {
    if (!this.isActive) {
      this.timer(this.intervalTime);
      this.isActive = true;
    }
    return this;
  }

  pause() {
    if (this.isActive) {
      this.isActive = false;
      this.clearTimer();
    }
    return this;
  }

  stop() {
    this.isActive = false;
    this.clearTimer();
    return this;
  }

  clearTimer() {
    window.clearTimeout(this.timeoutObject);
  }

  timer(time) {
    if (typeof this.action === 'function') {
      this.clearTimer();
      this.timeoutObject = window.setTimeout(
        () => {
          this.go();
        },
        isNaN(time) ? this.intervalTime : time
      );
    }
  }

  go() {
    if (this.isActive) {
      this.action();
      this.timer();
    }
  }
}
export default timer;
